package command;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class TaskManager {
    private static final Queue<Command> pendingTasks = new LinkedList<>();
    private static final List<Command> executedTasks = new ArrayList<>();
    private static final List<Command> undoneTasks = new ArrayList<>();

    public static void addTask(Command command) {
        pendingTasks.add(command);
        System.out.println("已添加任务: " + command.getDescription());
    }

    public static void executeAll() {
        System.out.println("\n开始执行任务队列...");
        while (!pendingTasks.isEmpty()) {
            Command command = pendingTasks.poll();
            command.execute();
            executedTasks.add(command);
            undoneTasks.clear(); // 新执行后清空撤销栈
        }
        System.out.println("所有任务执行完成");
    }

    public static void undoLast() {
        if (!executedTasks.isEmpty()) {
            Command command = executedTasks.remove(executedTasks.size() - 1);
            command.undo();
            undoneTasks.add(command);
        } else {
            System.out.println("没有可撤销的任务");
        }
    }

    public static void redoLast() {
        if (!undoneTasks.isEmpty()) {
            Command command = undoneTasks.remove(undoneTasks.size() - 1);
            command.execute();
            executedTasks.add(command);
        } else {
            System.out.println("没有可重做的任务");
        }
    }

    public static void displayPendingTasks() {
        System.out.println("\n待执行任务:");
        if (pendingTasks.isEmpty()) {
            System.out.println("(无待执行任务)");
            return;
        }

        int index = 1;
        for (Command task : pendingTasks) {
            System.out.println(index++ + ". " + task.getDescription());
        }
    }

    public static void displayExecutedTasks() {
        System.out.println("\n已执行任务:");
        if (executedTasks.isEmpty()) {
            System.out.println("(无历史任务)");
            return;
        }

        for (int i = 0; i < executedTasks.size(); i++) {
            System.out.println((i + 1) + ". " + executedTasks.get(i).getDescription());
        }
    }

    public static void cancelPendingTasks() {
        pendingTasks.clear();
        System.out.println("已清除所有待执行任务");
    }
}

